package com.huluobo.a2205monthdemo.login

import android.content.Intent
import android.util.Log
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2205monthdemo.MainActivity
import com.huluobo.a2205monthdemo.databinding.ActivityLoginBinding
import com.huluobo.base.bean.UserBean
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

/**
 *  Created by LC on 2024/9/29.
 */
@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding, LoginViewModel>() {
    override fun initData() {
        vm.loginSuccess.observe(this) {
            val userBean = Gson().fromJson(it, UserBean::class.java)
            ToastUtils.showLong("欢迎回来:${userBean.uName}")
            SPUtils.getInstance().put(Const.PARAM_TOKEN, userBean.token)
            SPUtils.getInstance().put(Const.PARAM_USERNAME, userBean.uName)
            SPUtils.getInstance().put(Const.PARAM_PASSWORD, userBean.uPwd)
            SPUtils.getInstance().put(Const.PARAM_UID, userBean.uId)
            vm.insertUserInfo(userBean)
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }

        vm.insertUserInfoSuccess.observe(this) {
            Log.i("TagA", "添加数据库:$it")
        }
    }

    override fun initView() {
        binding.loginHeader.headerTitle.text = "登录"
        binding.loginBtn.setOnClickListener {
            val username = binding.loginUsernameEt.text.toString()
            val password = binding.loginPasswordEt.text.toString()
            val timeString = (System.currentTimeMillis() / 1000).toString()
            val map = mutableMapOf<String, String>()
            map[Const.PARAM_USERNAME] = username
            map[Const.PARAM_PASSWORD] = password
            map[Const.PARAM_TIME] = timeString
            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            vm.login(body)
        }

        if (SPUtils.getInstance().getString(Const.PARAM_USERNAME).isNotEmpty() && SPUtils.getInstance()
                .getString(Const.PARAM_PASSWORD).isNotEmpty()
        ) {
            val map = mutableMapOf<String, String>()
            map[Const.PARAM_USERNAME] = SPUtils.getInstance().getString(Const.PARAM_USERNAME)
            map[Const.PARAM_PASSWORD] = SPUtils.getInstance().getString(Const.PARAM_PASSWORD)
            map[Const.PARAM_TIME] = (System.currentTimeMillis() / 1000).toString()
            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            vm.login(body)
        }
    }
}